﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.eLogistics;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Finance
{

      [Navigation("干线流程", "对帐管理")]
        [Function("eLogistics.RevenueMachineAccountManagement")]
    [PageTabber(Index = 0, NavigateUrl = "~/Finance/RevenueMachineAccountManagement.aspx", Title = "营收台帐管理", Type = typeof(RevenueMachineAccountManagement))]
    [PageTabber(Index = 1, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-StatementOfAccount.aspx", Title = "对帐管理", Type = typeof(RevenueMachineAccountManagement_StatementOfAccount))]
    [PageTabber(Index = 2, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-Invoice.aspx", Title = "开票管理", Type = typeof(RevenueMachineAccountManagement_Invoice))]
    [PageTabber(Index = 3, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-AccountsReceivable.aspx", Title = "收款管理", Type = typeof(RevenueMachineAccountManagement_AccountsReceivable))]

    public partial class RevenueMachineAccountManagement_StatementOfAccount : NavigationPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {
                PageQueryAdapter1.PageSize = 20;

                txtReceiptInfoActualResponseDateStart.Text =
 DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                txtReceiptInfoActualResponseDateEnd.Text =
    DateTime.Now.ToString("yyyy-MM-dd");
                txtReceivingOrderDateStart.Text =
DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                txtReceivingOrderDateEnd.Text =
    DateTime.Now.ToString("yyyy-MM-dd");

                txtActualShippingDateStart.Text =
DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                txtActualShippingDateEnd.Text =
    DateTime.Now.ToString("yyyy-MM-dd");
                this.ddlCustomer.InsertEmptyItem(ListEmptyType.Select);
                ddlCompany.InsertEmptyItem(ListEmptyType.Select);
                if (!this.IsSuperRoles())
                {
                    ddlCompany.SelectedValue = CurrentApplicationContext.CompanyId.ToString();
                    ddlCompany.Enabled = false;
                }

                PageQueryAdapter1.PerformQuery();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.PerformQuery();
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ObjectDataSourceCustomers.Selecting += (ds, dsArgs) =>
            {
                dsArgs.InputParameters["areaId"] = CurrentApplicationContext.CompanyId.ToString();
            };


        }

        public void ddlCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ddlCustomer.SelectedValue))
            {

                LoadGoodsShippedTypes(ddlCustomer.SelectedValue.ToGuid());
            }


        }

        private void LoadGoodsShippedTypes(Guid customerId)
        {
            this.ddlGoodsShippedTypeId.Items.Clear();
            this.ddlGoodsShippedTypeId.DataSource = ServiceContainer.GetService<ICustomerInfoService>().GetCustomerGoodsShippTypes(
               customerId, CurrentApplicationContext.CompanyId);
            this.ddlGoodsShippedTypeId.DataBind();
            ddlGoodsShippedTypeId.InsertEmptyItem(ListEmptyType.Select);
        }

        protected void PageQueryAdapter1_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {

            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            e.DataSource = service.SearchRevenueMachineAccountDataByCondition((RevenueMachineAccountSearchCriteria)e.Condition, gridOrderList.SortExpression,
                                                      gridOrderList.SortDirection, e.PageSize, e.PageIndex);

        }

        protected void PageQueryAdapter1_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            e.RecordCount = service.GetRevenueMachineAccountsCount((RevenueMachineAccountSearchCriteria)e.Condition);
        }

        protected void PageQueryAdapter1_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            var criteria = new RevenueMachineAccountSearchCriteria
            {
               
            };
            if (!MiscUtilities.IsNullOrEmpty(ddlCompany.SelectedValue))
            {
                criteria.AreaId = ddlCompany.SelectedValue.ToGuid();
            }

            if (!MiscUtilities.IsNullOrEmpty(ddlRouteTypeId.SelectedValue.ToGuid()))
            {
                criteria.RouteTypeId = ddlRouteTypeId.SelectedValue.ToGuid();
            }
            if (!string.IsNullOrEmpty(ddlGoodsShippedTypeId.SelectedValue))
            {
                criteria.GoodsShippedTypeId = ddlGoodsShippedTypeId.SelectedValue.ToGuid();
            }

            if (!MiscUtilities.IsNullOrEmpty(ddlCustomer.SelectedValue.ToGuid()))
            {
                criteria.CustomerId = ddlCustomer.SelectedValue.ToGuid();
            }
            DateTime? dateStart = null, dateEnd = null;
            if (!string.IsNullOrEmpty(txtReceiptInfoActualResponseDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtReceiptInfoActualResponseDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtReceiptInfoActualResponseDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtReceiptInfoActualResponseDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ReceiptInfoActualResponseDate = new Range<DateTime?>(dateStart, dateEnd);
            }

            if (!string.IsNullOrEmpty(txtReceivingOrderDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtReceivingOrderDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtReceivingOrderDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtReceivingOrderDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ReceivingOrderDate = new Range<DateTime?>(dateStart, dateEnd);
            }



            if (!string.IsNullOrEmpty(txtActualShippingDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtActualShippingDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtActualShippingDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtActualShippingDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ActualShippingDate = new Range<DateTime?>(dateStart, dateEnd);
            }

            if (!string.IsNullOrEmpty(txtOrderCode.Text))
            {
                criteria.OrderCode = txtOrderCode.Text.Trim();
            }

            if (!string.IsNullOrEmpty(txtTransportationPlanCode.Text))
            {
                criteria.TransportationPlanCode = txtTransportationPlanCode.Text.Trim();
            }

  
            if (radioIsStatementofAccountNeededYes.Checked)
            {
                criteria.IsStatementofAccountCompleted = true;
            }
            else if (radioIsStatementofAccountNeededNo.Checked)
            {
                criteria.IsStatementofAccountCompleted = false;
            }

            e.Condition = criteria;
        }

        protected void btnReload_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.ReloadCurrentPage();
        }

        protected void gridOrderList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var orderId = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));


                var btnViewDetail = (ImageButton)e.Row.FindControl("btnViewDetail");
                if (btnViewDetail != null)
                {
                    btnViewDetail.OnClientClick = string.Format("confirmOrder('{0}');return false;", orderId);
                }

                var btnConfirm = (ImageButton)e.Row.FindControl("btnConfirm");
                if (btnConfirm != null)
                {
                    btnConfirm.OnClientClick = string.Format("confirmOrder('{0}');return false;", orderId);
                }

                if (!MiscUtilities.IsNullOrEmpty(DataBinder.Eval(entity, "ProfitRate")) && Convert.ToDecimal(DataBinder.Eval(entity, "ProfitRate")) <0)
                {
                    e.Row.Style.Add("background-color", "#FF6600");

                }
            }
        }


        protected decimal GetProfitRate(object profit, object totalRevenues)
        {
            if (MiscUtilities.IsNullOrEmpty(totalRevenues)) return 0;
            if (MiscUtilities.IsNullOrEmpty(profit)) return 0;
            if (totalRevenues.ToString().ToDecimal() == 0) return 0;
            return Math.Round(((profit.ToString().ToDecimal() / totalRevenues.ToString().ToDecimal() ?? 0) * 100), 2);

        }


        protected string GetDeliveryAddress(object issuingId)
        {
            if (MiscUtilities.IsNullOrEmpty(issuingId)) return string.Empty;
            var orderService = ServiceContainer.GetService<IIssuingOrderService>();
            var issuingOrderDeliveryData = orderService.GetIssuingOrderDeliveryByOrderId(issuingId.ToString().ToGuid());

            return issuingOrderDeliveryData.Select(a => a.DeliveryAddress).Aggregate((a, b) => a + "," + b);

        }

        protected string GetShortDeliveryAddress(object issuingId)
        {
            var deliveryAddress = GetDeliveryAddress(issuingId);
            if (string.IsNullOrWhiteSpace(deliveryAddress) || deliveryAddress.Length <= 10)
                return deliveryAddress;
            return deliveryAddress.Substring(0, 10) + "...";

        }
    }
  }